import 'dart:async';
import 'dart:convert';

import 'package:mirror/Util.dart';
import 'package:mirror/api/UserApi.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

class WebSocketService {
  static WebSocketChannel? channel;

  static Timer? timer;

  static String userUid = "";

  static connect() async {
    var user = await UserApi.getUser();
    if (user == null) {
      Util.toast("用户不存在，websocket链接失败");
      return;
    }
    try {
      String ws =
          "ws://mirror.ging.plus/Chat-Service/WebSocket/${user.userUid}";
      channel = WebSocketChannel.connect(
        Uri.parse(ws),
      );
      channel?.stream.listen((message) {
        listenList.forEach((key, value) {
          value.call(message);
        });
      });
      userUid = "${(await UserApi.getUser())?.userUid}";
      startTimer();
    } catch (e) {
      print(e);
    }
  }

  static void removeListener(String s) {
    print("移除监听");
    listenList.remove(s);
  }

  static Map<String, dynamic> listenList = {};

  static addListener(String page, {required Function(dynamic result) func}) {
    print("添加监听");
    listenList[page] = func;
  }

  static send(s) {
    channel?.sink.add(s);
    print("发送的消息是：");
    print(s);
  }

  static void startTimer() {
    timer = Timer.periodic(const Duration(seconds: 10), (timer) {
      channel?.sink.add(jsonEncode(
          {'senderId': userUid, 'sentType': '3', 'content': '心跳消息-APP-镜'}));
    });
  }
}
